package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的拦截器
 */
public class WmTokenInterceptor implements HandlerInterceptor {
    /**
     * 执行目标方法之前执行的过滤器方法
     * @param request
     * @param response
     * @param handler
     * @return  true表示放行，false表示拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //TODO
        String token = request.getHeader("token");
        if(token==null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        if(claimsBody==null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //从已有的token中获取生成token所需的用户Id
        Long userId = claimsBody.get("id", Long.class);
        int i = AppJwtUtil.verifyToken(claimsBody);

        if(i==1||i==2){
            // token 无效，返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        } else if (i == 0) {
            // token 需要刷新，生成新 token
            String newToken = AppJwtUtil.getToken(userId);
             // 响应头返回新 token
            response.setHeader("token", newToken);
        }
        //4.放行
        WmUser user  = new WmUser();
        user.setId(Integer.valueOf(Math.toIntExact(userId)));
        WmThreadLocalUtil.setUser(user);
        return true;
    }

    /**
     * 完成所有的请求之后，执行的方法
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放资源
      //TODO
    }
}
